<template>
  <div class="bridge-demo">
    <div class="register-section">
      <h2>注册JS函数供原生调用</h2>
      <div class="input-group">
        <input v-model="registerFunctionName" placeholder="输入要注册的函数名" />
        <button @click="registerJsFunction">注册函数</button>
      </div>
      <div class="result" v-if="registerResult">
        <p>注册结果：{{ registerResult }}</p>
      </div>
    </div>

    <div class="call-section">
      <h2>调用原生函数</h2>
      <div class="input-group">
        <input v-model="callFunctionName" placeholder="输入要调用的原生函数名" />
        <input v-model="callFunctionParams" placeholder="输入调用参数" />
        <button @click="callNativeFunction">调用函数</button>
      </div>
      <div class="result" v-if="callResult">
        <p>调用结果：{{ callResult }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { registerHandler, callHandler } from '../utils/bridge';

// 注册函数相关
const registerFunctionName = ref('');
const registerResult = ref('');

// 调用函数相关
const callFunctionName = ref('');
const callFunctionParams = ref('');
const callResult = ref('');

// 注册JS函数供原生调用
const registerJsFunction = () => {
  if (!registerFunctionName.value) {
    registerResult.value = '请输入函数名';
    return;
  }

  registerHandler(registerFunctionName.value, (data, callback) => {
    registerResult.value = `收到原生调用，参数：${JSON.stringify(data)}`;
    callback({ received: true, data });
  });

  registerResult.value = `函数 ${registerFunctionName.value} 注册成功`;
};

// 调用原生函数
const callNativeFunction = async () => {
  if (!callFunctionName.value) {
    callResult.value = '请输入函数名';
    return;
  }

  try {
    const params = callFunctionParams.value ? JSON.parse(callFunctionParams.value) : null;
    const response = await callHandler(callFunctionName.value, params);
    callResult.value = `调用成功，返回结果：${JSON.stringify(response)}`;
  } catch (error) {
    callResult.value = `调用失败：${error}`;
  }
};
</script>

<style scoped>
.bridge-demo {
  max-width: 100%;
  margin: 0 auto;
  padding: 10px;
}

.register-section,
.call-section {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin-bottom: 10px;
}

h2 {
  font-size: 1.1em;
  margin: 0 0 8px 0;
}

input {
  width: 100%;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

button {
  width: 100%;
  padding: 6px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:hover {
  background-color: #45a049;
}

.result {
  margin-top: 8px;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
}
</style>